from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import random


def spider(driver):
    list_view = WebDriverWait(driver, 5).until(
        EC.presence_of_element_located((By.CLASS_NAME, "list-view"))
    )
    movie_tags = list_view.find_elements_by_tag_name('a')
    for movie_tag in movie_tags:
        movies.append(movie_tag.text)
    print("🚘 get {0}...".format(len(movies)))


def pagination(url):
    options = webdriver.FirefoxOptions()
    options.add_argument("headless")
    driver = webdriver.Firefox(options=options)
    driver.get(url)

    spider(driver)

    paginators = driver.find_elements_by_class_name('paginator')
    # 若只有一页 就没有分页了 因此要判断
    if len(paginators) > 0:
        # 直接点后页
        while True:
            nexts = driver.find_elements_by_class_name(
                'paginator')[0].find_element_by_class_name('next').find_elements_by_tag_name('a')
            if len(nexts) > 0:
                nexts[0].click()
                spider(driver)
            else:
                # 当后页没有a标签则跳出
                break
    driver.close()


def random_movies(count, num):
    all = list(range(1, count+1))
    return random.sample(all, num)


movies = []
index_url = "https://movie.douban.com/people/carpe-diem1018/wish?sort=time&amp;start=0&amp;filter=all&amp;mode=list&amp;tags_sort=count"
print("🌻 请输入你的豆瓣想看网址(默认回车):")
temp = input()
if temp:
    index_url = temp
print("🚗 开始抓取我想看的电影列表...")
pagination(index_url)
print("👏 已经抓取到{0}部[想看]电影".format(len(movies)))
print("😉 请输入数字 我将随机挑选几部电影供您选择:")
number = input()
print("⏱ 请稍等...")
time.sleep(1)
indexes = random_movies(len(movies), int(number))
print("🚩 Here It Is:")
i = 1
for index in indexes:
    print("{0}. {1}".format(i, movies[index]))
    time.sleep(0.5)
    i = i + 1
